//
//  MKMusicManager.m
//  singForYou
//
//  Created by nicolas on 2016/12/7.
//  Copyright © 2016年 nicolas. All rights reserved.
//

#import "MKMusicManager.h"
#import <AVFoundation/AVFoundation.h>

@interface MKMusicManager () {
    NSTimeInterval _currentTime;
}
//播放器
@property (strong, nonatomic) AVAudioPlayer *player;

@end

static MKMusicManager *_instance;

@implementation MKMusicManager

+ (void)load {
    //通过AVAudioSession向系统声明App使用的相关功能(音频)后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *error;
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    if (error) {
        NSLog(@"声明Category时出错:%@",error);
    }
    BOOL active = [session setActive:YES error:&error];
    if (active) {
        NSLog(@"active成功");
    }
}

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[MKMusicManager alloc] init];
    });
    return _instance;
}

- (BOOL)playMusic:(NSURL *)url {
    if (url == nil) {
        return NO;
    }
    //判断当前的url所对应的歌曲是否已经创建
    //同一首歌，继续播放，不用创建新的
    if (self.player && [self.player.url isEqual:url]) {
        if ([self.player isPlaying] == NO) {
            return [self.player play];
        }
    }
    //不是同一首歌，创建新的Player
    NSError *error;
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    if (error) {
        return NO;
    }
    return [self.player play];
}

- (void)pauseMusic {
    
    if (self.player && [self.player isPlaying]) {
        [self.player pause];
    }
    
}

- (void)stopMusic {
    
    if (self.player) {
        [self.player stop];
        [self.player setCurrentTime:0.0];
    }
    
}

#pragma mark - Getter & Setter

- (BOOL)isPlaying {
    
    if (self.player == nil) {
        return NO;
    }
    return self.player.isPlaying;
}

- (NSTimeInterval)duration {
    if (self.player == nil) {
        return 0;
    }
    return self.player.duration;
}

- (NSTimeInterval)currentTime {
    if (self.player == nil) {
        return 0;
    }
    return self.player.currentTime;
}

- (void)setCurrentTime:(NSTimeInterval)currentTime {
    _currentTime = currentTime;
    if (self.player) {
        self.player.currentTime = _currentTime;
    }
}

@end
